﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace LowLevelGraphics.ImageFormats
{
    /// <summary>
    /// Use this to load PBM files
    /// Monochrome File Format
    /// </summary>
    public class PBM : AbstractImageFormat, IImageFormat
    {
        /// <summary>
        /// returns Extension
        /// </summary>
        public override string Extension
        {
            get { return "pbm"; }
        }

        /// <summary>
        /// Creates the specified _s file name.
        /// </summary>
        /// <param name="_sFileName">Name of the _s file.</param>
        /// <returns></returns>
        public static UnsafeBitmap Create(string _sFileName)
        {
            //StreamReader reader = new StreamReader(_sFileName);
            //string sText = reader.ReadToEnd();      

            string[] aLine = Regex.Split(_sFileName, "\n|\t|\v\f\r ");
            //string[] aLine = Regex.Split(sText, "\n|\t|\v\f\r ");

            string sHeader = aLine[0];
            if (!sHeader.Contains("P1"))
            {
                Debug.WriteLine("Wrong Header Format, should be P1");
            }

            int nWidth = -1;
            int nHeight = -1;
            int i = 0;
            for (i = 1; i < aLine.Length; i++)
            {
                string sLine = aLine[i];

                //skip "#" comments
                string[] aElem = sLine.Trim().Split(' ');
                if (sLine.Trim().StartsWith("#")) continue;
                if (aElem.Length == 2) { nWidth = Convert.ToInt32(aElem[0]); nHeight = Convert.ToInt32(aElem[1]); break; }
            }
            int nStop = i + 1;
            UnsafeBitmap bitmap = new UnsafeBitmap(nWidth, nHeight);

            for (i = nStop; i < aLine.Length; i++)
            {
                string sLine = aLine[i];
                string[] aElem = sLine.Split(' ');
                for (int j = 0; j < aElem.Length; j++)
                {
                    bitmap.SetPixel(j, i, aElem[j] == "1" ? Definitions.Black: Definitions.White);
                }
            }
            return bitmap;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_sFileName"></param>
        /// <returns></returns>
        public override bool Save(string _sFileName)
        {
            throw new NotImplementedException();
        }
    }
}
